package com.briup.server;

import com.briup.entity.Environment;
import com.briup.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Collection;

public class DBStoreImpl implements DBStore {
    @Override
    /**
     * 保存所有采集的数据 到一张表
     */
    public void saveDB(Collection<Environment> collection) throws Exception {
        //获取连接
        Connection connection = JDBCUtil.getConnection();
        String sql = "insert into e_detail_0(id,name,srcId,descId,devId,count,cmd,status,data,gather_date) values(seq_0.nextval,?,?,?,?,?,?,?,?,?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        int i=0;
        for (Environment environment : collection) {
            //创建statement对象
            ps.setString(1,environment.getName());
            ps.setString(2,environment.getSrcId());
            ps.setString(3,environment.getDescId());
            ps.setString(4,environment.getDevId());
            ps.setInt(5,environment.getCount());
            ps.setString(6,environment.getCmd());
            ps.setInt(7,environment.getStatus());
            ps.setFloat(8,environment.getData());
            ps.setTimestamp(9,environment.getGatherDate());
            //添加sql到batch
            ps.addBatch();
            if (i++ == 5000) {
                ps.executeBatch();
                i=0;
            }
        }
        //执行sql
        ps.executeBatch();
        //关闭资源
        JDBCUtil.close(connection, ps);
    }
}
